package com.csxy.lxl.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csxy.lxl.entity.EduSubject;
import com.csxy.lxl.entity.excel.SubjetcData;
import com.csxy.lxl.exception.MyException;
import com.csxy.lxl.service.EduSubjectService;

public class SubjectExcelListtener extends AnalysisEventListener<SubjetcData> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListtener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public SubjectExcelListtener(){

    }



    // 一行一行读取excel内容
    @Override
    public void invoke(SubjetcData subjetcData, AnalysisContext analysisContext) {
        //判断excel中是否有类容，若无内容则抛出之定义异常
        if (subjetcData == null){
            throw new MyException(20001,"excel文件数据为空,读取异常！");
        }


        //一行一行的读，每次读取两个值，第一个值一级分类，第二个值 二级分类
        //判断是否有一级分类重复
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService,subjetcData.getOneSubjectName());
        if(existOneSubject == null){ //没有相同的一级分类，进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0"); //设置一级分类id值，0表示一级分类
            existOneSubject.setTitle(subjetcData.getOneSubjectName()); //设置一级分类名称
            eduSubjectService.save(existOneSubject);  //给数据库添加一级分类
        }
        //获取一级分类id值
        String parent_id = existOneSubject.getId();
        //判断二级分类是否重复
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, subjetcData.getTwoSubjectName(),parent_id);
        if (existTwoSubject == null) { //没有相同的二级分类，进行添加
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(parent_id); //设置二级分类id值
            existTwoSubject.setTitle(subjetcData.getTwoSubjectName()); //设置二级分类名称
            eduSubjectService.save(existTwoSubject); //给数据库添加二级分类
        }

    }

    private EduSubject existOneSubject(EduSubjectService eduSubjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService, String name, String parentId) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", parentId);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
